package com.goldplusgold.tradedelay.app.market.widget.chartview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.v4.view.NestedScrollingChild;
import android.text.Html;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

import com.goldplusgold.tradedelay.app.market.pojo.CrossBean;
import com.goldplusgold.tradedelay.app.market.pojo.StickData;
import com.goldplusgold.tradedelay.app.market.widget.chartutil.ColorUtil;
import com.goldplusgold.tradedelay.app.market.widget.listeners.ChartDetectorImpl;
import com.goldplusgold.tradedelay.app.market.widget.listeners.OnGestureAndScaleInterface;
import com.goldplusgold.tradedelay.app.market.widget.render.ChartRender;

import java.util.List;

/**
 * Created by Administrator on 2017/7/7.
 */

public abstract class BaseChartView<T> extends View implements ChartConstant, NestedScrollingChild ,OnGestureAndScaleInterface,CrossView.OnMoveListener {

    //分时图,K线高度
    protected float mainH;
    //指标高度
    protected float indexH;
    //指标左上y坐标
    protected float indexStartY;
    //时间左上Y坐标
    protected float timeStartY;
    //总宽
    protected int width;
    //总高
    protected int height;
    //十字线布局
    //双击监听，全屏
    protected ChartView.OnDoubleTapListener onDoubleTapListener;
    //十字线最后停下的点，当切换指标的时候，使用这个点来计算指标应该显示的文字
    private float lastX, lastY;
    //烛形图加空白的宽度和烛形图宽度之比
    public static final float WIDTH_SCALE = 1.1f;
    //烛形图和右侧空白的宽度
    public float DEFUALT_WIDTH = 15;
    //y轴最小值
    protected float xUnit;
    //chart 触摸文本消失监听
    protected KLineView.OnCrossListener onCrossListener;
    //一屏烛形图数量
    private int drawCount;
    //没两个烛形图x轴的距离
    private float candleXDistance;
    //当前画图偏移量（往右滑动之后）
    private CrossView crossView;

    private ChartDetectorImpl detector;

    protected List<T> datas;

    protected int sma_page_start_index = 0;

    protected int sma_page_end_inde = 0;

    private int offset;

    private T currentData;

    public BaseChartView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //关闭硬件加速，不然虚线显示为实线了
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        crossView = new CrossView(context,attrs);
        detector = new ChartDetectorImpl(context);
        crossView.setOnMoveListener(this);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        computeCountAndUnit();
    }

    public abstract void setDatas(List<T> list);


    /**
     * 获取长和宽 设置 crossview的大小
     */
    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        height = getMeasuredHeight();
        width = getMeasuredWidth();
        mainH = height * MAIN_SCALE;
        indexH = height * INDEX_SCALE;
        indexStartY = height - indexH;
        timeStartY = indexStartY - height * TIME_SCALE;
        crossView.measure(width,height);
    }

    /**
     * 计算每屏幕要显示的数量 和间距大小 还有起始索引
     */
    private void computeCountAndUnit() {
        if (datas == null && datas.size() == 0)
            return;
        drawCount = (int) (width / DEFUALT_WIDTH);
        candleXDistance = drawCount * WIDTH_SCALE;
        xUnit = width / drawCount;
        computePageIndex(offset);
    }

    /**
     * 计算数据列表的索引值
     */
    private  void computePageIndex(int offset) {
        if (offset != 0 && datas.size() - drawCount - offset < 0) {
            offset = datas.size() - drawCount;
        }
        int size = datas.size();
        sma_page_start_index = size - drawCount - offset;
        sma_page_end_inde = size - offset;
        if (size == 0) {
            return;
        }
        if (sma_page_end_inde >= size || sma_page_start_index >= size || sma_page_start_index >= size - drawCount) {
            sma_page_end_inde = size;
            sma_page_start_index = size - drawCount;
        }
        if (sma_page_start_index <= 0) {
            sma_page_start_index = 0;
        }
        if (size <= drawCount) {
            sma_page_start_index = 0;
            sma_page_end_inde = size;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        detector.onTouchEvent(event);
        return true;
    }

    public void setOnDoubleTapListener(ChartView.OnDoubleTapListener onDoubleTapListener) {
        this.onDoubleTapListener = onDoubleTapListener;
    }


    @Override
    public boolean onViewScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        if (datas != null && drawCount < datas.size() && Math.abs(distanceX) > DEFUALT_WIDTH) {
            int temp = offset + (int) (0 - distanceX / DEFUALT_WIDTH);
            if (temp > 0 && temp + drawCount <= datas.size()) {
                offset = temp;
                postInvalidate();
            }
            return true;
        }
        return false;
    }

    @Override
    public void onCrossMove(float x, float y) {
        lastX = x;
        lastY = y;
        if (this.datas == null)
            return;
        int position = (int) Math.rint(new Double(x) / new Double(DEFUALT_WIDTH));
        if (position > sma_page_end_inde - sma_page_start_index) {
            position = sma_page_end_inde - sma_page_start_index - 1;
        }
        if (position >= 1 && position < sma_page_end_inde - sma_page_start_index) {
            T cur = this.datas.get(sma_page_start_index+position);
            T pre = this.datas.get(sma_page_start_index+position - 1);
            currentData = cur;
            float xIn = (width / drawCount * position) + (width / candleXDistance / 2);
            onShowCrossData(cur, pre,xIn);
            postInvalidate();
        }
    }

    protected abstract void onShowCrossData(T cur, T pre,float x);

    /**
     * 缩放调整
     * @param detector
     * @return
     */
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        float scale = detector.getScaleFactor();
        //这个变化太快，把scale变 慢一点
        scale = 1 + ((scale - 1) * 0.4f);
        drawCount = (int) (width / DEFUALT_WIDTH);
        if (scale < 1 && drawCount >= datas.size()) {
            //缩小时，当缩到一屏显示完时，则不再缩小
        } else if (scale > 1 && drawCount < 20) {
            //放大时，当一屏少于20个时，则不再放大
        } else {
            DEFUALT_WIDTH = DEFUALT_WIDTH * scale;
            invalidate();
        }
        return false;
    }

    @Override
    public void onDismiss() {

    }
}
